package com.cmsz.walle.domain.core.impl;

import java.net.InetAddress;
import java.net.UnknownHostException;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import com.cmsz.walle.domain.core.Constant;
import com.cmsz.walle.domain.core.HostAgent;

public class HostAgentImpl implements HostAgent {

	private CuratorFramework zkclient = null;
	private String hostName;
	private String hostIp;
	private String agentName;
	private String znodeName;

	public HostAgentImpl() {
		try {
		//	znodeName = "/" + this.getHostName() + "-" + this.getHostIp();
			znodeName = "/" + this.getHostName();
			
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void register(String zkUrl) {
		if (zkclient == null) {
			zkclient = CuratorFrameworkFactory.builder().connectString(zkUrl).sessionTimeoutMs(5000).connectionTimeoutMs(3000).namespace(Constant.ZKP_NAMESPACE)
					.retryPolicy(new ExponentialBackoffRetry(1000, 10)).defaultData(null).build();
			zkclient.start();
		}

		try {
			Stat s = zkclient.checkExists().forPath(Constant.ZKP_HOSTS + znodeName);
			if (s == null) {
				zkclient.create().creatingParentsIfNeeded().forPath(Constant.ZKP_HOSTS + znodeName, this.getHostIp().getBytes());
				zkclient.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(Constant.ZKP_HOSTS + znodeName + "/living");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public String getHostName() throws UnknownHostException {
		if (hostName == null) {
			InetAddress ad;
			ad = InetAddress.getLocalHost();
			hostName = ad.getHostName();
		}
		return hostName;
	}

	public String getAgentName() {
		return this.agentName;
	}

	public String getHostIp() throws UnknownHostException {
		if (hostIp == null) {
			InetAddress ad;
			ad = InetAddress.getLocalHost();
			hostIp = ad.getHostAddress();
		}
		return hostIp;
	}
	
	

	public static void main(String[] args) {
		HostAgentImpl agent = new HostAgentImpl();
		agent.register("localhost:2181");

		try {
			Thread.sleep(1000000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
